# *****************************************************
# 实验文件夹: 02_functional_programming
# 作者: 李承硕
# *****************************************************

# 高阶函数 apply：接受一个列表和一个函数
def apply(arr, f):
    result = [0] * len(arr)   # 创建相同长度的结果数组
    for i in range(len(arr)):
        result[i] = f(arr[i])
    return result


# 示例函数1：求 2 倍
def double(x):
    return x * 2


# 示例函数2：求平方
def square(x):
    return x * x


# 示例函数3：加 10
def addTen(x):
    return x + 10


def print_array(prefix, arr):
    print(prefix, end="")
    print("[", end="")
    for i in range(len(arr)):
        print(arr[i], end="")
        if i < len(arr) - 1:
            print(", ", end="")
    print("]")  # 换行


def main():
    numbers = [1, 2, 3, 4, 5]

    print("原始数组: [1, 2, 3, 4, 5]")

    # 示例1：double
    doubled = apply(numbers, double)
    print_array("求2倍: ", doubled)

    # 示例2：square
    squared = apply(numbers, square)
    print_array("求平方: ", squared)

    # 示例3：addTen
    addedTen = apply(numbers, addTen)
    print_array("加10: ", addedTen)

    # 示例4：lambda 求3倍
    tripled = apply(numbers, lambda x: x * 3)
    print_array("求3倍(lambda): ", tripled)

    # 示例5：lambda 求负数
    negated = apply(numbers, lambda x: -x)
    print_array("求负数(lambda): ", negated)

    # 示例6：复合操作：x*2 + 5
    complex_arr = apply(numbers, lambda x: x * 2 + 5)
    print_array("乘2加5(lambda): ", complex_arr)


if __name__ == "__main__":
    main()
